<script setup lang="ts">
import {onMounted, onUnmounted, reactive, ref} from "vue";
import type {Ref} from 'vue';
import {clearCanvas, drawPointData, initCanvas,} from "@/js/home";
import {ElMessage, ElNotification} from "element-plus";
import type {FormInstance} from 'element-plus'
import {Message, MessageType, Player, R} from "@/js/home/data.d";
import {usePlayerStore} from "@/stores/player";


//store
let store = usePlayerStore();

//获取canvas
const canvas = ref<HTMLCanvasElement>()
const ws: WebSocket = new WebSocket(`ws://${window.location.host}/api/ws`)

//是否显示修改框
const editInfoRef = ref()
const msgRef = ref()
const msgs: string[] = reactive([])
const key: Ref<string> = ref('')
//表单内容
const form = reactive({
    info: {
        // TODO 修改
        visible: true,
        form: {
            name: '',
        },
        rules: {
            name: [{required: true, message: '游戏名称不能为空', trigger: 'blur'}]
        }
    },
    msg: {
        form: {
            msg: ''
        },
        rules: {
            msg: [{required: true, message: '内容不能为空', trigger: 'blur'}]
        }
    }
})


//按钮显示控制
const btnsVisible = reactive({
    start: false,
    join: true,
    clear: false,
    sendBox: false
})

//加入游戏列表人员
const players: Ref<Player[]> = ref([])

//处理信息
ws.onmessage = (e: MessageEvent) => {
    const r = JSON.parse(e.data) as R<Message>
    if (r.code !== 200) {
        ElMessage({
            type: 'error',
            message: r.msg
        })
        return
    }
    const data = r.data
    console.log('收到数据：', data)
    switch (data.type) {
        case MessageType.START:
            //开始游戏
            if (!btnsVisible.start) {
                //如果之前我加入游戏的时候我的位置不是第一位则显示发送聊天信息按钮
                btnsVisible.sendBox = true
            } else {
                btnsVisible.sendBox = false
            }
            break;
        case MessageType.MESSAGE:
            ElNotification({
                message: data.data,
                position: 'top-left',
                duration: 800
            })
            //信息
            break;
        case MessageType.DRAW:
            //如果是自己绘画则不回显内容
            if (store.isMeDraw) {
                return
            }
            drawPointData(data.data)
            //绘画信息
            break;
        case MessageType.JOINSUCCESS:
            //游戏加入成功
            if (data.data === 0) {
                //判断是否为第一位加入游戏的人，如果是的话就显示开始按钮
                btnsVisible.start = true
            } else {
                btnsVisible.start = false
            }
            btnsVisible.join = false
            break;
        case MessageType.JOIN:
            //加入游戏信息
            break;
        case MessageType.EDIT:
            //修改信息
            break;
        case MessageType.NEXT:
            store.isMeDraw = false
            btnsVisible.clear = false
            btnsVisible.join = false
            btnsVisible.sendBox = true
            btnsVisible.start = false
            key.value = ''
            break
        case MessageType.INFOS:
            //获取所有游戏用户信息
            players.value = data.data
            break
        case MessageType.GAMEOVER:
            gameOver()
            break
        case MessageType.COMPERE:
            //成为主持人
            key.value = JSON.parse(data.data).title
            store.isMeDraw = true
            btnsVisible.clear = true
            btnsVisible.start = false
            btnsVisible.sendBox = false
            btnsVisible.join = false
            break
        default :
            break;
    }
}

//记录画图的数据
let graph: any;

//页面挂载之后
onMounted(() => {
    graph = initCanvas(canvas.value as HTMLCanvasElement, ws)
})

//页面卸载之后
onUnmounted(() => {
    //关闭ws连接
    ws.close()
})

//加入游戏
const joinGame = () => {
    ws.send(Message.json(MessageType.JOIN, null))
}

//开始游戏
const startGame = () => {
    ws.send(Message.json(MessageType.START, null))
}

//游戏结束
const gameOver = () => {
    ElMessage({
        type: 'info',
        message: '游戏结束！'
    })
    //清空画图区域
    graph.context.clearRect(0, 0, graph.width, graph.height)
    //设置为未加入游戏的时候状态
    btnsVisible.sendBox = false
    btnsVisible.start = false
    btnsVisible.clear = false
    btnsVisible.join = true
    //设置不是我来绘制图形
    store.isMeDraw = false
}

const sendMessage = (formEl: FormInstance | undefined) => {
    if (!formEl) {
        return
    }
    formEl.validate((valid: boolean) => {
        if (valid) {
            ws.send(Message.json(MessageType.MESSAGE, form.msg.form.msg))
            form.info.visible = false
            form.msg.form.msg = ''
        }
    })
}

//提交修改信息
const editInfo = (formEl: FormInstance | undefined) => {
    if (!formEl) {
        return
    }
    formEl.validate((valid: boolean) => {
        if (valid) {
            ws.send(Message.json(MessageType.EDIT, new Player(null, form.info.form.name, 0, 0)))
            form.info.visible = false
        }
    })
}

</script>

<template>
    <div class="w-100 h-100">
        <div class="p-2 text-center fs-2">
            {{ key }}
        </div>
        <div class="container box rounded p-1">
            <div class="w-100 h-100">
                <canvas ref="canvas" class="bg-white rounded position-relative"></canvas>
                <div class="position-absolute bottom-0 start-0">
                    <div class="p-1 rounded bg-gradient" v-for="(v,index) in msgs" :key="index">
                        {{ v }}
                    </div>
                </div>
            </div>
        </div>
        <el-form :rules="form.msg.rules" :model="form.msg.form" ref="msgRef" class="w-100" v-show="btnsVisible.sendBox">
            <el-form-item prop="msg" class="w-100 d-flex is-justify-space-between">
                <div class="flex-fill">
                    <el-input v-model="form.msg.form.msg"/>
                </div>
                <div>
                    <el-button type="primary" @click="sendMessage(msgRef)">发送</el-button>
                </div>
            </el-form-item>

        </el-form>
        <div class="mt-3">
            <el-button type="primary" @click="startGame" v-show="btnsVisible.start">开始</el-button>
            <el-button type="primary" @click="joinGame" v-show="btnsVisible.join">加入游戏</el-button>
            <el-button type="danger" @click="clearCanvas" v-show="btnsVisible.clear">清除画布</el-button>
            <el-button type="warning" @click="form.info.visible = true">修改我的信息</el-button>
        </div>
        <div class="py-2">
            <div class="grid">
                <el-badge v-for="(v,index) in players" :key="index" class="g-col-4 m-1" :value="v.scope">
                    <el-avatar size="large">
                        {{ v.name.length > 4 ? v.name.substring(0, 3) + '...' : v.name }}
                    </el-avatar>
                </el-badge>
            </div>
        </div>
        <el-dialog title="修改我的信息" :close-on-click-modal="false" :model-value="form.info.visible" width="300px"
                   :show-close="false">
            <el-form
                ref="editInfoRef"
                :model="form.info.form"
                :rules="form.info.rules"
            >
                <el-form-item prop="name">
                    <el-input v-model="form.info.form.name" placeholder="请输入游戏名称"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="editInfo(editInfoRef)">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss">
.box {
    height: 400px;
    background-color: #888;
}
</style>
